<template>
  <div class="xyt-home">
    <!-- <img class="xyt-nmc-pool" src="../assets/img/nmc.png" alt="" @click="goNmc"> -->
    <img class="home-bg" src="../assets/img/bg.png" alt="">
    <!-- <div class="xyt-online-share" @click="share">分享好友</div> -->
    <div class="xyt-online-person" @click="goOwnFly('online')">在线好友 {{ friendsNum }}
      <div class="xyt-online" v-show="curUser.number > 0">
        <div class="xyt-user" id="user">
          <span>+{{ curUser.number }}</span>
        </div>
      </div>
    </div>
    <div class="xyt-list">
      <div class="xyt-item" @click="send">
        <img src="../assets/img/fjr.png" alt="">
      </div>
      <div class="xyt-item" @click="acquireFly" id="acquireFly">
        <img src="../assets/img/fjj.png" alt="">
      </div>
      <div class="xyt-item" @click="goOwnFly('')">
        <img src="../assets/img/fjo.png" alt="">
      </div>
    </div>
    <div class="xyt-game" id="fenji"></div>
    <TalkSend ref="talkSend"></TalkSend>
    <TalkList ref="talkList"></TalkList>
    <TalkMessage ref="talkMessage" @replay="replay"></TalkMessage>
    <TalkReplayVue ref="talkReplayVue"></TalkReplayVue>
  </div>
</template>
<script setup>
import { onMounted, reactive, ref, onUnmounted } from 'vue';
import TalkSend from './../components/talk/TalkSend.vue'
import phaserGame from '../assets/js/game'
import TalkList from '../components/talk/TalkList.vue'
import { capChatPaperPlan } from './../api/fly.js'
import TalkMessage from './../components/talk/TalkMessage.vue'
import TalkReplayVue from '../components/talk/TalkReplay.vue';
import { Toast } from 'vant'
import { initWebSocket, share } from './../utils/utils.js'
import { queryUserFriendList } from './../api/fly.js'
import useWs from './../utils/useWs.js'
import { useRouter } from 'vue-router'
import C from './../utils/constant.js'

let router = useRouter()
let friendList = []
let friendsNum = ref(0)
let userIds = []
let userList = reactive([])
let userIndex = 0
let stagingNum = 0
let stagingCount = 3
let curUser = ref({
  user_id: '',
  name: '',
  icon_url: '',
  chat_id: '',
  status: 'show',
  number: 0
})
let talkSend = ref(null)
let talkList = ref(null)
const talkMessage = ref(null)
const talkReplayVue = ref(null)
let fly = {}

function send() {
  talkSend.value.open()
}

function goOwnFly(status) {
  let userStatus = {}
  friendList.forEach(friend => {
    userStatus[friend.user_id] = friend.online_status
  });
  talkList.value.open(userStatus, status)
}

// 获取飞机
async function acquireFly() {
  const res = await capChatPaperPlan()
  if (res && res.result && res.result.content) {
    fly = res.result
    talkMessage.value.open({
      paper_plane_id: res.result.paper_plane_id,
      content: res.result.content
    })
  } else {
    Toast('纸飞机已被领取完啦，休息一会再来吧~')
  }
}

// 回复
function replay() {
  talkReplayVue.value.open(fly)
}

onMounted(() => {
  console.log('onMounted')
  phaserGame.phaserInit()
  anime({
    targets: '#acquireFly',
    duration: 2000,
    keyframes: [
      {scale: 1},
      {scale: 1.2},
      {scale: 1}
    ],
    easing: 'cubicBezier(.5, .05, .1, .3)',
    loop: true
  })
  setInterval(() => {
    // 用户动画
    switch (curUser.value.status) {
      case 'show':
        anime({
          targets: '#user',
          translateY: -20,
          duration: 1000,
          easing: 'linear',
          opacity: 1
        })
        curUser.value.status = 'staging'
        break;
      case 'staging':
        if (stagingNum < stagingCount) {
          stagingNum++
        } else {
          stagingNum = 0
          curUser.value.status = 'hide'
        }
        break;
      case 'hide':
        anime({
          targets: '#user',
          translateY: -40,
          duration: 1000,
          easing: 'linear',
          opacity: 0
        })
        curUser.value.status = 'destroy'
        break;
      case 'destroy':
        anime({
          targets: '#user',
          translateY: 0,
          duration: 100,
          easing: 'linear',
          opacity: 0
        })
        if (userIndex < userList.length - 1) {
          userIndex++
        } else {
          userIndex = 0
        }
        curUser.value.status = 'show'
        curUser.value.number = 0
        break;
    
      default:
        break;
    }
  }, 1000);
  getOnLineList()
  initWebSocket()
  share({
    title: '象牙塔: 纸飞机大厅',
    desc: '神秘又好玩的纸飞机游戏，快来跟我一起参与吧',
    link: location.href,
    imgUrl: 'https://miai-1310370640.cos.ap-shanghai.myqcloud.com/share_photo/zhifeiji.jpg',
    success: function (res) {
      // 设置成功
    },
    fail: function(error) {
      console.log('error', error)
    }
  })
})

onUnmounted(() => {
  phaserGame.destroy()
})

useWs({
  systemPushMessage: systemPushMessage
})

// 获取好友在线列表
async function getOnLineList() {
  userList.length = 0
  const res = await queryUserFriendList()
  friendList = res.result
  let num = 0
  res.result.forEach(item => {
    if (item.online_status === 1) {
      userList.push(item)
      ++num
    }
  }); 
  friendsNum.value = num
  getUserIds()
}
function systemPushMessage(data) {
  switch (data.reason) {
    case 'USER_JOIN_ROOM':
      console.log(data)
      let index = userIds.indexOf(data.body.external_user_id)
      if (index !== -1) {
        let has = false
        userList.forEach(user => {
          if (user.user_id === data.body.external_user_id) {
            has = true
          }
        });
        if (!has) {
          friendList[index].online_status = 1
          userList.push(friendList[index])
          friendsNum.value = friendsNum.value + 1
          curUser.value.number += 1
        }
      }
      break;
    case 'USER_LEAVE_ROOM':
      break
    default:
      break;
  }
}

function getUserIds() {
  userIds = []
  friendList.forEach(user => {
    userIds.push(user.user_id)
  });
}

function goNmc() {
  router.push({
    path: '/anonymityPool'
  })
}


</script>
<style lang="scss" scoped>
.xyt-home {
  margin: auto;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  .home-bg {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: -1;
    width: 100%;
    height: 100%;
  }
}
.xyt-desc {
  display: block;
  color: #CC19C4;
  margin-bottom: 20px;
}
.xyt-user {
  position: absolute;
  right: -30px;
  top: 0;
  color: #fff;
  opacity: 0;
  img {
    width: 32px;
    height: 32px;
    vertical-align: middle;
    margin-right: 6px;
    border-radius: 50%;
  }
}
.xyt-list {
  position: absolute;
  bottom: 30px;
  left: 0;
  right: 0;
  text-align: center;
  display: flex;
  .xyt-item {
    flex: 1;
  }
  img {
    height: 60px;
  }
}
.xyt-game {
  padding-top: 60px;
}
.xyt-online-person {
  z-index: 9;
  position: absolute;
  left: 10px;
  top: 20px;
  line-height: 20px;
  border-radius: 10px;
  min-width: 80px;
  padding: 0 10px;
  text-align: center;
  background: rgba(0, 0, 0, 0.18);
  color: #fff;
  font-size: 12px;
}
.xyt-online-share {
   z-index: 6;
  position: absolute;
  right: 10px;
  top: 20px;
  line-height: 20px;
  border-radius: 10px;
  min-width: 80px;
  padding: 0 10px;
  text-align: center;
  background: rgba(0, 0, 0, 0.18);
  color: #fff;
  font-size: 12px;
}
.xyt-nmc-pool {
  position: absolute;
  top: 20px;
  right: 16px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  z-index: 6;
}
</style>